<template>
	<div>
      <el-form ref="form" :model="form" :rules="form.safetyCheckOpt!=3?rules:rules1" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务创建" prop="createTime">
              {{form.createTime}} 由 {{form.createBy}} 创建
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div style="float:right;">
              <el-button
                    :class="addItem.review?'dis_active':'active'"
                    type="text"
                    @click="addItem.review=addItem.review?false:true"
                >任务复核</el-button>
                <el-button
                :class="addItem.copy?'dis_active':'active'"
                    type="text"
                    @click="addItem.copy=addItem.copy?false:true"
                >任务抄送</el-button>
            </div>
          </el-col>
        </el-row>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称"
						size="small" class="form_long1"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安检类型" prop="safetyCheckOpt">
              <el-select v-model="form.safetyCheckOpt" placeholder="请选择安检类型"
									size="small" class="form_short">
                <el-option
                  v-for="dict in safetyCheckOptOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安检模板" prop="safetyTemplateOptArray">
                <el-select multiple v-model="form.safetyTemplateOptArray" placeholder="请选择安检模板"
                    size="small" class="form_short">
                  <el-option
                    v-for="dict in safetyTemplateOptOptions"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id + ''"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
        </el-row>
        <el-row :span="12">
            <el-form-item v-if="form.safetyCheckOpt!=3"  label="检查对象" prop="checkTargetOrgs" >
                  <el-select :value="selectCheckTargetOrgs" @clear="clearSelect('checkTargetOrgs')"
                    size="small" multiple placeholder="请选择检查对象" clearable class="form_long" @remove-tag='removeOrgTag'></el-select>
                  <el-button type="primary" @click="selectTargetOrgs" plain>选择二级单位</el-button>
            </el-form-item>
        </el-row>
        <el-form-item v-if="form.safetyCheckOpt!=3" label="检查人员" prop="checkUsers">
          <div class="select_view" >
            <el-select :value="selectCheckUsers" @clear="clearSelect('checkUsers')"
							size="small" multiple placeholder="请选择检查人员" clearable class="form_long" @remove-tag='removeCheckUserTag'></el-select>
              <el-button type="primary" @click="selectUser(1)" plain >选择用户</el-button>
          </div>
        </el-form-item>
        <el-form-item label="任务复核" v-if="addItem.review">
          <div class="select_view">
            <el-select :value="selectReviewUsers" @clear="clearSelect('reviewUsers')"
							size="small" multiple placeholder="请选择任务抄送" clearable class="form_long" @remove-tag='removeReviewUserTag'></el-select>
            <el-button type="primary" @click="selectUser(2)" plain >选择用户</el-button>
          </div>
        </el-form-item>
        <el-form-item label="任务抄送" v-if="addItem.copy">
          <div class="select_view">
            <el-select :value="selectCopyToUsers" @clear="clearSelect('copyToUsers')"
							size="small" multiple placeholder="请选择任务抄送" clearable class="form_long" @remove-tag='removeCopyUserTag'></el-select>
            <el-button type="primary" @click="selectUser(3)" plain >选择用户</el-button>
          </div>
        </el-form-item>
        <el-row v-if="form.safetyCheckOpt!=3">
          <el-col :span="12" >
            <el-form-item  label="任务周期" prop="taskCycleOpt" >
            <el-select v-model="form.taskCycleOpt" @change="changeTaskCycleOpt" placeholder="请选择任务周期"
							size="small" class="form_short">
              <el-option
                v-for="dict in taskCycleOptOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="12">
             <el-form-item label="周期频次" prop="checkFrequencyOpt">
               <el-select
							 		:disabled="form.taskCycleOpt == '1'"
									v-model="form.checkFrequencyOpt"
									@change="changeCheckFrequencyOpt"
									placeholder="请选择周期版次"
									size="small" class="form_short">
                 <el-option
                   v-for="dict in checkFrequencyOptOptions"
                   :key="dict.dictValue"
                   :label="dict.dictLabel"
                   :value="dict.dictValue"
                 ></el-option>
               </el-select>
             </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务开始" prop="startDate">
              <el-date-picker clearable size="small" class="form_short"
                v-model="form.startDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择任务开始">
              </el-date-picker>
            </el-form-item>
            </el-col>
            <el-col :span="12">
             <el-form-item label="任务结束" prop="endDate">
               <el-date-picker clearable size="small" class="form_short"
                 v-model="form.endDate"
                 type="date"
                 format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                 placeholder="选择任务结束">
               </el-date-picker>
             </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="整改报告" prop="rectificationTypeOpt">
              <el-select v-model="form.rectificationTypeOpt" placeholder="请选择整改报告"
									size="small" class="form_short">
                <el-option
                  v-for="dict in rectificationTypeOptOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="整改期限" prop="rectificationPeriod">
                <el-input v-model="form.rectificationPeriod" placeholder="检查结束后第N个工作日"
									size="small" class="form_short" type="number"/>
             </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务详情" prop="taskDescription">
          <el-input v-model="form.taskDescription" type="textarea" placeholder="请输入内容"
						size="small" class="form_long1" rows="4"/>
        </el-form-item>
        <el-form-item label="任务附件">
					 <UploadCom ref="upload"
					 @submitData="submitData"
					 description="点击选择需要上传的文件"
					 :userFileList="fileList"
            class="form_long" />
        </el-form-item>
      </el-form>
      <ChooseOrgan ref="chooseOrgan" @chooseOrgs ="setCheckTargetOrgs" ></ChooseOrgan>
      <ChooseUser ref="chooseEmployee" @chooseUsers ="setChooseUsers" ></ChooseUser>
	</div>
</template>
<script>
import { listLabsafetyCheckIndex } from "@/api/labsafety/labsafetyCheckIndex";
import { addLabsafetyForm, updateLabsafetyForm } from "@/api/labsafety/labsafetyForm";
import ChooseUser from "../../safetyCompents/check_user.vue"
import ChooseOrgan from "../../safetyCompents/choose_organ.vue"
import UploadCom from "@/views/labdata/commons/upload.vue"
export default {
  name: "CreateDialog",
  components: {ChooseUser, ChooseOrgan, UploadCom},
	props: {
		form: Object
	},
  data() {
    return {
			checkTargetOrgs: [],
      checkUsers: [],
			reviewUsers: [],
      copyToUsers: [],
      // 安全检查单表格数据
      labsafetyFormList: [],
      // 安检类型字典
      safetyCheckOptOptions: [],
      // 任务周期字典
      taskCycleOptOptions: [],
      // 整改报告字典
      rectificationTypeOptOptions: [],
      // 安检模板字典
      safetyTemplateOptOptions: [],
      // 周期版次字典
      checkFrequencyOptOptions: [],
      addItem: {
        review: false, //任务复核
        copy: false //任务抄送
      },
      fileList: [],
      // 表单校验
      rules: {
        taskName: { required: true, message: "任务名称不能为空", trigger: "blur" },
        safetyCheckOpt: { required: true, message: "安检类型不能为空", trigger: "blur" },
        safetyTemplateOptArray: { required: true, message: "安检模板不能为空", trigger: "change" },
        startDate: { required: true, message: "任务开始不能为空", trigger: "blur" },
        rectificationTypeOpt: { required: true, message: "整改报告不能为空", trigger: "change" },
        rectificationPeriod: { required: true, message: "整改期限不能为空", trigger: "blur" },
        checkTargetOrgs: { required: true, message: '检查对象不能为空', trigger: 'change' },
        checkUsers: { required: true, message: '检查人员不能为空', trigger: 'change' },
        taskCycleOpt: { required: true, message: '任务周期不能为空', trigger: 'change' },
        checkFrequencyOpt: { required: true, message: '周期频次不能为空', trigger: 'change' }
      },
      rules1: {
        taskName: { required: true, message: "任务名称不能为空", trigger: "blur" },
        safetyCheckOpt: { required: true, message: "安检类型不能为空", trigger: "blur" },
        safetyTemplateOptArray: { required: true, message: "安检模板不能为空", trigger: "change" },
        startDate: { required: true, message: "任务开始不能为空", trigger: "blur" },
        rectificationTypeOpt: { required: true, message: "整改报告不能为空", trigger: "change" },
        rectificationPeriod: { required: true, message: "整改期限不能为空", trigger: "blur" }
      }
    };
  },
  created() {
    this.reset();
    this.getDicts("safetyCheckOpt").then(response => {
      this.safetyCheckOptOptions = response.data;
    });
    this.getDicts("taskCycleOpt").then(response => {
      this.taskCycleOptOptions = response.data;
    });
    this.getDicts("rectificationTypeOpt").then(response => {
      this.rectificationTypeOptOptions = response.data;
    });
    // this.getDicts("safetyTemplateOpt").then(response => {
    //   this.safetyTemplateOptOptions = response.data;
    // });
    this.getDicts("checkFrequencyOpt").then(response => {
      this.checkFrequencyOptOptions = response.data;
    });
		listLabsafetyCheckIndex().then(response => {
      this.safetyTemplateOptOptions = response.rows
		});
  },
  computed: {
      selectCheckTargetOrgs() {
        return this.checkTargetOrgs.map(item => item.orgName)
      },
      selectCheckUsers() {
        return this.checkUsers.map(item => item.nickName)
      },
      selectReviewUsers() {
        return this.reviewUsers.map(item => item.nickName)
      },
      selectCopyToUsers() {
        return this.copyToUsers.map(item => item.nickName)
      }
  },
  methods: {
    removeOrgTag(item){
      for(var i=0;i<this.checkTargetOrgs.length;i++){
        if(this.checkTargetOrgs[i].orgName==item){
          this.checkTargetOrgs.splice(i,1);
          i--;
        }
      }
    },
    removeCheckUserTag(item){
      this.removeTag(item,this.checkUsers);
    },
    removeReviewUserTag(item){
      this.removeTag(item,this.reviewUsers);
    },
    removeCopyUserTag(item){
      this.removeTag(item,this.copyToUsers);
    },
    removeTag(item, userList){
      for(var i=0;i<userList.length;i++){
        if(userList[i].nickName==item){
          userList.splice(i,1);
          i--
        }
      }
    },
    selectTargetOrgs() {
      this.$refs["chooseOrgan"].handleAdd(this.checkTargetOrgs);
    },
    // 安检类型字典翻译
    safetyCheckOptFormat(row) {
      return this.selectDictLabel(this.safetyCheckOptOptions, row.safetyCheckOpt);
    },
    // 任务周期字典翻译
    taskCycleOptFormat(row) {
      return this.selectDictLabel(this.taskCycleOptOptions, row.taskCycleOpt);
    },
    // 整改报告字典翻译
    rectificationTypeOptFormat(row) {
      return this.selectDictLabel(this.rectificationTypeOptOptions, row.rectificationTypeOpt);
    },
    // 安检模板字典翻译
    safetyTemplateOptFormat(row) {
      return this.selectDictLabel(this.safetyTemplateOptOptions, row.safetyTemplateOpt);
    },
    // 周期版次字典翻译
    checkFrequencyOptFormat(row) {
      return this.selectDictLabel(this.checkFrequencyOptOptions, row.checkFrequencyOpt);
    },
    selectUser(chooseType){
      let choosedUser = this.checkUsers;
      //不做用户过滤限制
     /* if(chooseType==1){
        this.$refs["chooseEmployee"].handleAdd(choosedUser,chooseType,this.checkTargetOrgs);
        return;
      } */
      if(chooseType==2){
        choosedUser = this.reviewUsers;
      }else if(chooseType==3){
        choosedUser = this.copyToUsers;
      }
      this.$refs["chooseEmployee"].handleAdd(choosedUser,chooseType);

    },
    // 表单重置
    reset() {
      //this.form = {};
      this.addItem = {
        review: false,
        copy: false
      }
			this.checkTargetOrgs = []
      this.checkUsers = []
			this.reviewUsers = []
      this.copyToUsers = []
			this.fileList = []
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.safetyCheckId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
    },
    /** 修改按钮操作 */
    handleUpdate() {
    },
    /** 提交按钮 */
    submitForm() {
      //console.log("call submit");
      this.$refs["form"].validate(valid => {
        if (valid) {
					this.$refs["upload"].doSubmit();
        }
      });
    },
    setChooseUsers(list, callType){
      if(callType==1){
        this.setCheckUsers(list);
      }else if(callType==2){
        this.setReviewUsers(list);
      }else if(callType==3){
        this.setCopyToUsers(list);
      }
    },
    setCheckUsers(list) {	// 检查人员
			this.checkUsers = list
      this.form.checkUsers = '';
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.checkUsers += ','
        }
        this.form.checkUsers += item.userId
      });
      //console.log(JSON.stringify(this.form.checkUsers))
    },
    setReviewUsers(list) {	// 复核人员
			this.reviewUsers = list
      this.form.reviewUsers = ''
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.reviewUsers += ','
        }
        this.form.reviewUsers += item.userId
      });
    },
    setCopyToUsers(list) {	// 抄送人员
      this.copyToUsers = list
      this.form.copyToUsers = ''
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.copyToUsers += ','
        }
        this.form.copyToUsers += item.userId
      });
    },
    setCheckTargetOrgs(list) { // 检查对象
			this.checkTargetOrgs = list;
      this.checkUsers = [];
      this.form.checkTargetOrgs = '';
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.checkTargetOrgs += ','
        }
        this.form.checkTargetOrgs += item.orgId
      });
      this.$forceUpdate();
      //console.log('this.form.checkTargetOrgs='+this.form.checkTargetOrgs);
    },
		clearSelect(type) {
			switch (type) {
				case 'checkUsers':
					this.setCheckUsers([])
					break;
				case 'reviewUsers':
					this.setReviewUsers([])
					break;
				case 'copyToUsers':
					this.setCopyToUsers([])
					break;
				case 'checkTargetOrgs':
					this.setCheckTargetOrgs([])
					break;
				default:
					break;
			}
		},
		changeTaskCycleOpt(taskCycleOptVal) {
			if (taskCycleOptVal == "1") {
				this.$set(this.form, "checkFrequencyOpt", "1")
			} else {
				this.$set(this.form, "checkFrequencyOpt", "")
			}
		},
		changeCheckFrequencyOpt(checkFrequencyOptVal) {
			if (this.form.taskCycleOpt == "2" && checkFrequencyOptVal == "1") {
        this.msgError("重复任务周期，周期频次不能为无");
				this.$set(this.form, "checkFrequencyOpt", "")
			}
		},
		/** 提交按钮 */
		submitData(allFiles) {
			this.form.files = allFiles
      if(this.form.checkTargetOrgs && this.form.checkTargetOrgs.length==0){
        this.form.checkTargetOrgss = null;
      }
      if(this.form.checkUsers && this.form.checkUsers.length==0){
        this.form.checkUsers = null;
      }
			if (this.form.instanceId != null) {
				updateLabsafetyForm(this.form).then(response => {
					this.msgSuccess("修改成功");
					this.$emit("updateForm", response.data)
				});
			} else {
				addLabsafetyForm(this.form).then(response => {
					this.msgSuccess("新增成功");
					this.$emit("updateForm", response.data)
				});
			}
		}
  }
};
</script>
<style type="text/css" scoped lang="scss">
  .form_long{
    width:458px;
  }
  .form_long1{
    width:556px;
  }
  .form_short{
    width:220px;
  }
  /deep/ .el-button.active{
    text-decoration: underline;
    color: #0000ee;
  }
  /deep/ .el-button.dis_active {
    color: #999999
  }
  .select_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .button_view {
      display: flex;
      align-content: center;
      justify-content: center;
  }
</style>
